#!/bin/bash

readonly PWD0="$(dirname "$(readlink -fn "$0")")"
readonly SNIPPETS_SRC=./snippets
readonly SNIPPETS_DST=~/.config/Code/User/snippets

# 创建目录
function create_directory() {
    local directory=${1}
    if [ ! -e ${directory} ]; then
        mkdir -p ${directory}
    fi
}

# 复制文件
function copy_file() {
    local src_path="${1}" # 源文件路径
    local dst_path="${2}" # 目标文件路径

    cp -f "${src_path}" "${dst_path}"
    echo "copy ${dst_path}"
}

# 递归复制文件（复制原有结构）
function recurse_copy() {
    local src_path="${1}" # 源文件路径
    local dst_path="${2}" # 目标文件路径

    if [ -d "${src_path}" ]; then
        create_directory "${dst_path}"

        for file in $(ls ${src_path}); do
            recurse_copy "${src_path}/${file}" "${dst_path}/${file}"
        done
    elif [ -f "${src_path}" ]; then
        copy_file "${src_path}" "${dst_path}"
    fi
}

# snippets 文件复制
function direct_copy() {
    local src_path="${1}" # 源文件路径
    local dst_path="${2}" # 目标文件路径
    local basename="${3:-}" # 前缀

    if [ -d "${src_path}" ]; then
        if [ ! -z "${basename}" ]; then
            basename="${basename}-"
        fi

        for file in $(ls ${src_path}); do
            direct_copy "${src_path}/${file}" "${dst_path}" "${basename}${file}"
        done
    elif [ -f ${src_path} ]; then
        copy_file ${src_path} "${dst_path}/${basename}"
    fi
}

function install() {
    direct_copy "${SNIPPETS_SRC}" "${SNIPPETS_DST}"
}

function uninstall() {
    rm -f ${SNIPPETS_DST}/*.code-snippets
}

function print_help() {
    echo "Usage: $0 [install|uninstall]"
    echo "  install    Install snippets"
    echo "  uninstall  Uninstall snippets"
}

function main() {
    cd "${PWD0}"

    #### ==========================================================================
    if [ $# -eq 0 ]; then
        install
        exit 1
    fi

    case ${1} in
        install)
            install
            ;;
        uninstall)
            uninstall
            ;;
        *)
            print_help
            exit 1
            ;;
    esac
}

main $@